package com.falcon.mvc.aop;

import com.falcon.mvc.core.RequestAttrHolder;
import com.falcon.mvc.core.ResponseWrapper;
import com.falcon.mvc.enums.RequestAttrNameEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/** 将 Rest 接口响应值，统一包装成 BaseResponse 格式
 * @author zongf
 * @date 2024-02-08
 **/
@Slf4j
//@Component
//@WebFilter
//@Order(2)
@Deprecated
public class BaseResponseFilter implements Filter {

    @Autowired
    private RequestAttrHolder requestAttrHolder;

    private List<String> ignoreUrlPatten = new ArrayList<>();

    public BaseResponseFilter() {
        ignoreUrlPatten.add(".html");
        ignoreUrlPatten.add(".css");
        ignoreUrlPatten.add(".js");
        ignoreUrlPatten.add("/api-docs/");
    }

    private boolean ignoreUri(String requestUri) {

        return ignoreUrlPatten.stream()
                .anyMatch(urlPattern -> requestUri.contains(urlPattern));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;

        try {
            // 处理请求
            if (ignoreUri(servletRequest.getRequestURI())) {
                chain.doFilter(request, response);
            } else {
                this.handleRequest(request, response, chain);
            }
        }finally {
            // 清理所有线程变量
            requestAttrHolder.clearAll();
        }

    }

    private void handleRequest(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 设置字符集编码格式为: UTF8
        response.setCharacterEncoding("UTF-8");

        // 自定义 response, 记录请求响应数据、状态码等
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);

        // 调用目标接口
        chain.doFilter(request, responseWrapper);

        int responseCode = 0;
        String responseMessage = null;
        String responseData = null;

        // 处理响应结果
        if (responseWrapper.isOccurError()) {
            responseCode = responseWrapper.getErrorCode();
            responseMessage = responseWrapper.getErrorMessage();
        } else {
            responseData = new String(responseWrapper.getResponseData(), StandardCharsets.UTF_8);
        }
        if (!StringUtils.hasText(responseData)) {
            responseData = "null";
        }

        StringBuilder contentSb = new StringBuilder();
        contentSb.append("{")
                .append("\"code\":").append(responseCode).append(",")
                .append("\"message\":").append(responseMessage).append(",")
                .append("\"data\":").append(responseData)
                .append("}");

        // 如果需要打印响应结果
        Boolean logSuccess = requestAttrHolder.get(RequestAttrNameEnum.LOG_RESPONSE);
        if (Optional.ofNullable(logSuccess).orElse(true)) {
            log.info("响应结果:{}", contentSb);
        }

        // 返回数据
        PrintWriter out = response.getWriter();
        out.print(contentSb);
        out.flush();
        out.close();

    }


}
